package com.study.jyg.rxjava2study.widget;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.UserHandle;
import android.widget.Toast;

public class MyBroadcast {

    public static final  String BROADCAST_ACTION_FIRST = "com.ceshi.guangbo.first";
    public static final  String BROADCAST_ACTION_SECOND = "com.ceshi.guangbo.second";
    public static final  String BROADCAST_ACTION_THREE = "com.ceshi.guangbo.three";

    /**
     * 发送广播
     * @param context
     */
    public static void sendBroadCast(Context context){
        Intent intent = new Intent();
        Bundle bundle = new Bundle();
        bundle.putString("text", "我发送广播了，你收到了么？");
        intent.putExtras(bundle);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction( BROADCAST_ACTION_FIRST);
        context.sendBroadcast(intent);//无序广播
    }

    /**
     * 注册广播(方法1.动态注册)
     */
    public static void registerBroadCast(Context context){
        IntentFilter filter = new IntentFilter();
        filter.addAction(BROADCAST_ACTION_FIRST);//可以设置多个action 用于接收多个广播，此处只用了一个
//        filter.addAction(BROADCAST_ACTION_SECOND);
//        filter.addAction(BROADCAST_ACTION_THREE);
        context.registerReceiver( new MyTestBroadCast(),  filter);
    }


    /**
     * 自定义广播
     */
    public static class MyTestBroadCast extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            if ( "com.ceshi.guangbo.first".equals(intent.getAction())){
                Toast.makeText(context, null == intent.getExtras()? "没有发送数据" : intent.getExtras().getString("text", "没有发送数据"), Toast.LENGTH_SHORT).show();
            }
        }
    }
}
